package com.oocl.ita.serverlistenner;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.SocketException;

import com.oocl.ita.handler.IHandler;
import com.oocl.ita.parser.Parser;
import com.oocl.ita.qqclientt.QQClient;
import com.oocl.ita.sakura.protocol.Protocol;

public class ServerListener implements Runnable {
	private Parser parser;
	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Runnable#run()
	 * 
	 * 1. 监听服务器传来的Protocol ois.readObject 
	 * 2. Parser 解析Protocol，返回Handler 
	 * 3. handler处理Protocol
	 */
	
	

	public void run() {
		System.out.println("ServerListener : "  + QQClient.getClient());
		ObjectInputStream ois = QQClient.getOis();
		while (true) {
			System.out.println("ServerListener : " + QQClient.getClient() +" keep reading protocol loop");
			try {
				Protocol protocol = (Protocol) ois.readObject();
				System.out.println("ServerListener : " + QQClient.getClient() +" " + protocol);
				IHandler handler = parser.parse(protocol);
				handler.handle(protocol);
			} catch (SocketException e) {
				System.out.println("ServerListener : " + QQClient.getClient() +" we lost the connection");
				e.printStackTrace();	
				break;
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}



	public ServerListener() {
		super();
		this.parser = new Parser();
	}

}
